package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.LoginAnnotation;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.IRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor{
    @Autowired
    private IRedisService redisService ;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //这里实现拦截操作
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //判断方法上是否贴有登录的注解
        if(handlerMethod.hasMethodAnnotation(LoginAnnotation.class)){
            //从请求头中获取到token
            String token = request.getHeader("token");
            UserInfo user = redisService.checkVal(token);
            //判断用户是否登陆过
            if(user == null){
                //没有登录过
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        return true;
    }
}
